import {
  Component,
  createRef,
  type ChangeEvent,
  type KeyboardEvent,
} from "react";

export interface ITodo {
  id: string;
  title: string;
  isDone: boolean;
}

interface IProps {
  id: string;
  title: string;
  isDone: boolean;
  onChange: (todo: ITodo) => void;
  onDelete: (id: string) => void;
}

export default class TodoItem extends Component<IProps> {
  state = {
    isEdit: false, // 表示当前是否处于编辑状态
  };

  editInputRef = createRef<HTMLInputElement>();

  onChange = (e: ChangeEvent<HTMLInputElement>) => {
    // 1. 获取当前元素的 checked
    const checked = e.target.checked;
    console.log("checked", checked);
    // 2. 通知父组件，调用父组件传递过来的函数
    this.props.onChange({
      id: this.props.id,
      title: this.props.title,
      isDone: checked,
    });
  };

  onClick = () => {
    if (window.confirm("是否确认删除")) {
      this.props.onDelete(this.props.id);
    }
  };

  onDoubleClick = () => {
    // 1. 修改 isEdit 为 true
    this.setState(
      () => ({ isEdit: true }),
      () => {
        // 2. 让出现的输入框获取焦点
        // console.log(this.editInputRef.current);
        this.editInputRef.current?.focus();
      }
    );
  };

  onKeyUp = (e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      // 告诉父组件做修改
      this.props.onChange({
        id: this.props.id,
        title: (e.target as HTMLInputElement).value,
        isDone: this.props.isDone,
      });
      // 去除编辑状态
      this.setState({ isEdit: false });
    }
  };

  render() {
    const { title, isDone } = this.props;
    const { isEdit } = this.state;

    return (
      <li className="todo">
        {isEdit ? (
          <div className="view">
            <input
              ref={this.editInputRef}
              type="text"
              className="edit"
              defaultValue={title}
              onKeyUp={this.onKeyUp}
            />
          </div>
        ) : (
          <div className="view">
            <input
              className="toggle"
              type="checkbox"
              checked={isDone}
              onChange={this.onChange}
            />
            <label className="label" onDoubleClick={this.onDoubleClick}>
              {title}
            </label>
            <button className="destroy" onClick={this.onClick}>
              ×
            </button>
          </div>
        )}
      </li>
    );
  }
}
